package com.ruoyi.bizsys.utils;

import com.ruoyi.bizsys.dto.UserInfo;
import com.ruoyi.bizsys.service.IAppUserService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 用户对象
 * 用于缓存获取，注册和实名需要删除此缓存
 * @author cyh
 * @date 2022-04
 */
@Slf4j
@Component
@AllArgsConstructor
public class UserCacheService {

    private RedisCache redisCache;

    private TokenService tokenService;

    private IAppUserService appUserService;

    private static final String USER_CACHE_INFO_KEY = "userCacheInfo:";

    /**
     * 获取用户用户缓存信息
     * @param userId
     * @return
     */
    public UserInfo getUserCacheInfo(String userId) {
        String redisKey = getUserCacheInfoKey(userId);
        UserInfo userInfo = redisCache.getCacheObject(redisKey);
        if (userInfo == null) {
            userInfo = getUserInfoByUserId(userId);
            redisCache.setCacheObject(redisKey, userInfo, 30, TimeUnit.DAYS);
        }
        return userInfo;
    }

    /**
     * 获取用户用户缓存信息
     * @return
     */
    public UserInfo getUserCacheInfo() {
        return getUserCacheInfo(getUserId());
    }

    /**
     * 获取用户UserId
     *
     * @return
     */
    public String getUserId() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser == null || Func.isEmpty(loginUser.getUsername())) {
            log.warn("用户不存在或登录态失效");
            throw new BusinessException(RspEnmu.ILLEGAL_USER_REQ_ERR);
        }
        return loginUser.getUsername();
    }

    /**
     * 查询用户信息
     * @param userId
     * @return
     */
    public UserInfo getUserInfoByUserId(String userId) {
        // todo 实名需要删除redis
        return appUserService.getUserInfoByUserId(userId);
    }

    /**
     * 查询用户信息
     * @param custCo
     * @return
     */
    public UserInfo getUserInfoByCustNo(String custCo) {
        return appUserService.getUserInfoByCustNo(custCo);
    }

    /**
     * 删除用户缓存信息
     * （用户更新信息后删除缓存）
     * @return
     */
    public void removeUserCache(String userId) {
        redisCache.deleteObject(getUserCacheInfoKey(userId));
    }


    /**
     * 获取用户缓存KEY
     * @param userId
     * @return
     */
    public String getUserCacheInfoKey(String userId) {
        return USER_CACHE_INFO_KEY + userId;
    }

}
